//
//  WZPersonalController.m
//  ETong
//
//  Created by wanzhao on 15/10/28.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZPersonalController.h"
#import "WZMineCell.h"
#import "WZMineItem.h"
#import "WZGroupItem.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "WZHelpController.h"
#import "WZUserInfoController.h"
#import "WZUpdateController.h"
#import "WZSettingController.h"
#import "MBProgressHUD+WZ.h"
#import "WZRootViewController.h"
#import "NetWorkShare.h"
#import "UIBarButtonItem+category.h"
#import "SSKeychain.h"


@interface WZPersonalController ()<UITableViewDataSource, UITableViewDelegate, WZMineCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
- (WZGroupItem *)addGroupMineItem;
@property (nonatomic, strong) NSMutableArray *sectionItemArray;
@property (nonatomic, strong) CContactModel *curAccount;


@end

@implementation WZPersonalController

- (void)dealloc
{
    NSLog(@"WZPersonalController dealloc");
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR(238, 238, 238);
    
   
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"title" title:nil target:self sel:@selector(lookPersonalInformation) titleFont:Font18 titleColor:ClearColor];
    self.navigationItem.title = @"个人中心";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, HARDWARE_SCREEN_HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = ClearColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.scrollEnabled = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.view addSubview:self.tableView];
    
    //读取当前用户信息
    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.curAccount = [[[CContactMgr alloc] init] loadContactWithUserCode:acc.userName];
    
    [self setupSection0];
    [self setupSection1];
    [self setupSection2];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    if (!IsIOS7) {
        self.navigationController.navigationBar.tintColor = RGBCOLORWITH16COLOR(0x354d6c);
    } else {
        self.navigationController.navigationBar.barTintColor = RGBCOLORWITH16COLOR(0x354d6c);
    }
    
    [MBProgressHUD showMessage:nil toView:nil];
    [NetWorkShare checkMobileWithUserId:self.curAccount.UserID successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD hideHUDForView:nil];
         NSString *mobileStr = @"";
        if (responseObject) {
            NSString *status =  [NSString stringWithFormat:@"%@",responseObject[@"status"]];
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                if ([status isEqualToString:@"2"]) {
                    mobileStr = @"已认证";
                    
                } else {
                    
                }
                
            } else {
                
                if ([status isEqualToString:@"-1"]) {
                    
                } else if ([status isEqualToString:@"0"]) {
                    
                } else if ([status isEqualToString:@"1"]) {
                    mobileStr = @"待审核";
                } else if ([status isEqualToString:@"3"]) {
                    mobileStr = @"审核被拒绝";
                }
                
            }
            
        } else {
            
        }
        [USER_DEFAULT setObject:mobileStr forKey:ISMOBILEAVALable];
        [USER_DEFAULT synchronize];
        
        WZGroupItem *group = self.sectionItemArray[1];
        WZMineItem *item4 = group.itemArray[3];
        if (M_ISSTRNULL(mobileStr)) {
            item4.title = @"手机认证";
            item4.isHiddenBackView = YES;
        } else {
            item4.title = [NSString stringWithFormat:@"手机认证(%@)",mobileStr];
            item4.isHiddenBackView = NO;
        }
        item4.isHiddenAccessView = YES;

        
        [self.tableView reloadData];
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:nil];

    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [[NSNotificationCenter defaultCenter] postNotificationName:ADDGUESTURE object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [[NSNotificationCenter defaultCenter] postNotificationName:REMOVEGUESTURE object:nil];
}
- (void)lookPersonalInformation
{
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    nav.navigationBarHidden = NO;
    self.navigationController.navigationBarHidden = YES;
    
    WZUserInfoController *info = [[WZUserInfoController alloc] init];
    [nav pushViewController:info animated:YES];
}

- (void)setupSection0
{
    WZMineItem *item = [WZMineItem mineItemWithTitle:self.curAccount.UserName icon:@"personal_title"];
    item.isHiddenBackView = YES;
    item.subTitle = [NSString stringWithFormat:@"\n\n%@   %@",self.curAccount.DEPNAME,self.curAccount.Position];
    item.isHiddenAccessView = NO;
    item.destVc = [WZUserInfoController class];
    item.isHeadImage = YES;
    
    WZGroupItem *groupItem = [self addGroupMineItem];
    groupItem.itemArray = @[item];

}

- (void)setupSection1
{
    WZMineItem *item = [WZMineItem mineItemWithTitle:@"设置" icon:@"setting_image"];
    item.isHiddenAccessView = NO;
    item.isHiddenBackView = YES;
    item.destVc = [WZSettingController class];
    
    WZMineItem *item2 = [WZMineItem mineItemWithTitle:@"系统更新" icon:@"update_set_image"];
    item2.isHiddenAccessView = NO;
    item2.isHiddenBackView = YES;
    item2.destVc = [WZUpdateController class];
    
    WZMineItem *item3 = [WZMineItem mineItemWithTitle:@"帮助中心" icon:@"help_image"];
    item3.isHiddenAccessView = NO;
    item3.isHiddenBackView = YES;
    item3.destVc = [WZHelpController class];
    
    WZMineItem *item4 = [WZMineItem mineItemWithTitle:@"手机认证" icon:@"help_image"];
    NSString *mobleStr = [USER_DEFAULT stringForKey:ISMOBILEAVALable];
    if (M_ISSTRNULL(mobleStr)) {
        item4.title = @"手机认证";
        item4.isHiddenBackView = YES;
    } else {
        item4.title = [NSString stringWithFormat:@"手机认证(%@)",mobleStr];
        item4.isHiddenBackView = NO;
    }
    item4.isHiddenAccessView = YES;
    
    
    WZGroupItem *groupItem = [self addGroupMineItem];
    groupItem.itemArray = @[item,item2,item3,item4];
    
}

- (void)setupSection2
{
    WZMineItem *item = [WZMineItem mineItemWithTitle:@"退出账户" icon:@"out_login_account"];
    item.isHiddenAccessView = YES;
    item.isHiddenBackView = YES;
    item.block = ^(){
        [MBProgressHUD showMessage:nil toView:self.view];
        [NetWorkShare loginOutOAWithUserId:self.curAccount.UserID successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
             [MBProgressHUD hideHUDForView:self.view];
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                NSUserDefaults *userDefault = USER_DEFAULT;
                [userDefault setBool:YES forKey:ISFORCEQUIT];
                [userDefault synchronize];
                
            //判断是否清空缓存
                if ([userDefault boolForKey:ISClEARMEMORY]) {
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        __block NSFileManager *fileMg = [NSFileManager defaultManager];
                        NSArray *array = [fileMg subpathsOfDirectoryAtPath:USER_DOCUMENT error:nil];
                        [array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                            if ([fileMg fileExistsAtPath:obj]) {
                                [fileMg removeItemAtPath:obj error:nil];
                            }
                        }];
 
                    });
                }
                
                UIApplication *app = [UIApplication sharedApplication];
                app.statusBarHidden = NO;
                app.statusBarStyle = UIStatusBarStyleLightContent;
            
                
                
            
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
           
        
            
        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view];
            
            [MBProgressHUD show:@"网络异常" icon:nil view:self.view];
        }];
    };
    
    
    WZGroupItem *groupItem = [self addGroupMineItem];
    groupItem.itemArray = @[item];
}


- (NSMutableArray *)sectionItemArray
{
    if (_sectionItemArray == nil) {
        _sectionItemArray = [NSMutableArray array];
    }
    return _sectionItemArray;
}

- (WZGroupItem *)addGroupMineItem
{
    WZGroupItem *item = [WZGroupItem groupMineItem];
    [self.sectionItemArray addObject:item];
    return item;
}

- (NSArray *)sectionArray
{
    return self.sectionItemArray;
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionItemArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.sectionItemArray[section] itemArray].count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger count = [tableView numberOfRowsInSection:indexPath.section];
    
    WZMineCell *cell = [WZMineCell mineCellWithTableView:tableView];
    WZGroupItem *item = self.sectionItemArray[indexPath.section];
    if (count == 1 || indexPath.row == count - 1) {
        cell.line.hidden = YES;
    } else {
        cell.line.hidden = NO;
    }
    cell.item = item.itemArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = ClearColor;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return OppositeHeightRate(15);
    } else {
        return OppositeHeightRate(20);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return OppositeHeightRate(88);
    }
    return OppositeHeightRate(45);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WZGroupItem *groupitem = self.sectionItemArray[indexPath.section];
    WZMineItem *item = groupitem.itemArray[indexPath.row];
    
    if (indexPath.section == 1 && indexPath.row == 3) {
        
        [MBProgressHUD showMessage:nil toView:self.view];
        NSString *uuID = [SSKeychain passwordForService:[NSBundle mainBundle].bundleIdentifier account:@"DeviceUUID"];
        [NetWorkShare certifyMobileWithUserId:self.curAccount.UserID phone:@"" simUuid:@"" mobileUuid:uuID successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                if (responseObject) {
                    
                    if ([[responseObject objectForKey:@"success"] boolValue]) {
                        [MBProgressHUD showSuccess:@"待审核"];
                        [USER_DEFAULT setObject:@"待审核" forKey:ISMOBILEAVALable];
                        [USER_DEFAULT synchronize];
                        item.title = @"待审核";
                        item.isHiddenBackView = NO;
                        [self.tableView reloadData];
                        
                    } else {
                        if ([responseObject[@"message"] isKindOfClass:[NSNull class]]) {
//                            NSLog(@"hahahahah");
                            [MBProgressHUD showError:@"认证失败"];
                        } else {
                            [MBProgressHUD showError:responseObject[@"message"]];
                        }
                        
                    }
                    
                } else {
                    [MBProgressHUD showError:@"未知错误"];
                }
                
            } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showError:@"网络错误"];
            }];
    }
    if (item.block != nil) {
        item.block();
    }
    
    if (item.destVc) {
        UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        nav.navigationBarHidden = NO;
        self.navigationController.navigationBarHidden = YES;
        
        UIViewController *vc = [[item.destVc alloc] init];
        [nav pushViewController:vc animated:YES];
    }

}


@end
